﻿using System;
using System.IO;
using System.Windows.Forms;

namespace SubFps
{
    public partial class MainForm : Form
    {
        public MainForm()
            : this(null)
        {

        }
        public MainForm(string fileName)
        {
            InitializeComponent();
            if (fileName != null)
            {
                TxtFile.Text = fileName;
            }
        }
        private void BtnConver_Click(object sender, EventArgs e)
        {
            SrtFixArgs args;
            if (!ValidateFields(out args))
                return;
            var fixer = new SrtFixer(args);
            if (Helper.TryInvoke(() => fixer.FixSrt()))
                Helper.ShowInfo("Srt has been fixed successfully");
        }
        private void BtnBrowse_Click(object sender, EventArgs e)
        {
            using (var openFile = new OpenFileDialog())
            {
                openFile.Filter = "SRT Files|*.srt";
                openFile.DefaultExt = "srt";
                openFile.Title = "Browse to the subtitle file";
                openFile.InitialDirectory = Helper.TryGetDirectoryName(TxtFile.Text);
                if (openFile.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                    return;
                TxtFile.Text = openFile.FileName;
            }
        }
        private void BtnRevert_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to revert?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != System.Windows.Forms.DialogResult.Yes)
                return;
            if (Helper.TryInvoke(() => SrtFixer.RevertFromFileName(TxtFile.Text.Trim('\"'))))
                Helper.ShowInfo("Reverted to original file");
        }
        private bool ValidateFields(out SrtFixArgs args)
        {
            args = new SrtFixArgs();

            try
            {
                args.CurrentFPS = double.Parse(TxtCurrentFps.Text);
                args.OutFPS = double.Parse(TxtOutFps.Text);
                args.FileName = TxtFile.Text;
                args.Delay = (long)DelayNum.Value;
                return true;
            }
            catch (Exception ex)
            {
                Helper.ShowError(ex.Message, "Please Input Correct Data");
                return false;
            }
        }

        private void BtnClose_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

    }
}
